package lxs.swift.tool;

import lxs.swift.operation.Try;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Constructor;
import java.util.Objects;

public class Errors {
    public static <E extends Throwable> E create(@NotNull Class<E> eClass) {
        Objects.requireNonNull(eClass);
        return Try.valueOf(() -> {
            //获取公开构造
            Constructor<E> constructor = eClass.getConstructor();
            return constructor.newInstance();
        }).ret();
    }

    public static <E extends Throwable> E create(@NotNull Class<E> eClass, String error) {
        Objects.requireNonNull(eClass);
        return Try.valueOf(() -> {
            //获取公开构造
            Constructor<E> constructor = eClass.getConstructor(String.class);
            return constructor.newInstance(error);
        }).ret();
    }

    /**
     * 无害化，避免显式抛出
     */
    public static <E extends RuntimeException, TE extends Throwable> E harmless(@NotNull TE te) {
        if (te instanceof RuntimeException) {
            return ((E) te);
        }
        return (E) new RuntimeException(te);
    }
}
